package cn.ingrun.utils.auth;

import cn.ingrun.utils.redisUtil.RedisUtil;
import cn.ingrun.utils.stringUtil.StringUtils;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service
public class AuthServerImpl implements AuthServer {
    private final int tokenLength = 30;
    private RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public Boolean isLogin() {
        String token = getToken();
        if (token.length() != tokenLength){
            return false;
        }
        return !StringUtils.isNullOrEmpty(redisUtil.get(token));
    }

    @Override
    public String login(String id, long time) {
        String token = StringUtils.randomString(tokenLength);
        redisUtil.set(token, id, time);
        return token;
    }

    @Override
    public Boolean logout() {
        String token = getToken();
        if (StringUtils.isNullOrEmpty(token)){
            return false;
        }
        return redisUtil.del(token);
    }

    @Override
    public String getLoginUserID() {
        String token = getToken();
        if (StringUtils.isNullOrEmpty(token)){
            return "";
        }
        return redisUtil.get(token);
    }

    @Override
    public String getToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return "";
        }
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtil.isNullOrEmpty(token)) {
            return "";
        }

        return token;
    }

    @Override
    public long getTokenExpireTime() {
        return redisUtil.getExpire(getToken());
    }
}
